package com.ezerg.boot.shiro.test;

import java.util.Arrays;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class IniRealm {
	public static void main(String[] args) {
        // 读取配置文件，初始化SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 获取securityManager实例
        SecurityManager securityManager = factory.getInstance();
        // 把securityManager实例绑定到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 创建token令牌，用户名/密码
        UsernamePasswordToken token = new UsernamePasswordToken("admin", "password");
        // 得到当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        try{
            // 身份认证
            currentUser.login(token);
            System.out.println("身份认证成功！");
            String role = "role2";
            boolean b = currentUser.hasRole(role);
            System.out.println("是否有角色 ["+role+"]=" + b);
            String permission = "user:select";
            b = currentUser.isPermitted(permission);
            System.out.println("是否有角色 ["+permission+"]=" + b);
            //
            //测试hasRoles
            boolean[] results = currentUser.hasRoles(Arrays.asList("role1","role2","role3"));
            System.out.println(results[0]? "有role1这个角色" : "没有role1这个角色");
            System.out.println(results[1]? "有role2这个角色" : "没有role2这个角色");
            System.out.println(results[2]? "有role3这个角色" : "没有role3这个角色");            
        }catch(AuthenticationException e){
            e.printStackTrace();
            System.out.println("身份认证失败！");
        }
        // 退出
        currentUser.logout();
    }
}
